package org.viva.macro.cms;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.viva.admin.util.page.Page;
import org.viva.service.cms.ContentService;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Service("cms_content_page")
public class ContentPageDirective implements TemplateDirectiveModel {

    @Resource
    private ContentService contentService;

    @SuppressWarnings({ "rawtypes", "deprecation", "unchecked" })
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        if (params.isEmpty()) params = new HashMap<>();
        Page page = contentService.getPage(params);
        env.setVariable("page", ObjectWrapper.DEFAULT_WRAPPER.wrap(page));
        body.render(env.getOut());
    }

}
